//
//  MyLoanVC.m
//  MRBang
//
//  Created by 铅笔 on 16/5/12.
//  Copyright © 2016年 杭州易网新科技. All rights reserved.
//

#import "MyLoanVC.h"

#import "MyLoanCell.h"

#import "MyLoanModel.h"

#define CELLHEIGHT 158*PROPORTION_WIDTH

static int from =0;

@interface MyLoanVC ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) UITableView *tableView_myLoan;
@property (nonatomic,strong) NSMutableArray *mutableArray_data;//存放所有数

@end

@implementation MyLoanVC

- (NSMutableArray *)mutableArray_data
{
    if (!_mutableArray_data) {
        _mutableArray_data = [[NSMutableArray alloc] init];
    }
    return _mutableArray_data;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的贷款";
    
    [self initWithMyLoanVCSubviews];
    //网络请求
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self DataSourceRequestHelpMeBagBankListView];
    
    [self setUprefresh];
    [self setTopRefresh];
}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.mutableArray_data removeAllObjects];
}

#pragma mark -- 创建视图
- (void) initWithMyLoanVCSubviews
{
    self.tableView_myLoan = [[UITableView alloc] initWithFrame:CGRectMake(0,0, kScreenWidth, kScreenHeight+64)];
    [self.view addSubview:self.tableView_myLoan];
    self.tableView_myLoan.dataSource = self;
    self.tableView_myLoan.delegate = self;
    self.tableView_myLoan.showsVerticalScrollIndicator = NO;
    self.tableView_myLoan.backgroundColor = COLOR_EVERYVIEWBG;
    self.tableView_myLoan.separatorStyle = UITableViewCellSeparatorStyleNone;
}

#pragma mark --- UITableViewDataSource
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.mutableArray_data.count;
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellMyLoanID = @"cellMyLoanID";
    MyLoanCell *cell_bagList = [tableView cellForRowAtIndexPath:indexPath];
    if (cell_bagList==nil) {
        cell_bagList = [[MyLoanCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellMyLoanID];
    }
    cell_bagList.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (self.mutableArray_data.count!=0) {
        
        [cell_bagList initWithCarRecordModel:self.mutableArray_data[indexPath.row]];
    }
    
    UIView *view_line = [[UIView alloc] initWithFrame:CGRectMake(27*PROPORTION_WIDTH, CELLHEIGHT-1, kScreenWidth, 1.0)];
    [cell_bagList.contentView addSubview:view_line];
    view_line.backgroundColor = [BaseViewController colorWithHexString:@"#EEEFF1"];
    
    return cell_bagList;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return CELLHEIGHT;
}

#pragma mark - 集成下拉刷洗 上拉加载
- (void)setUprefresh
{
    __weak __typeof(self) weakSelf = self;
    
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.tableView_myLoan.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [weakSelf loadNewData];
    }];
    
    // 马上进入刷新状态
    //    [self.tableView.header beginRefreshing];
}

- (void)setTopRefresh
{
    
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [footer setTitle:@"暂无更多记录!" forState:MJRefreshStateNoMoreData];
    // 设置footer
    self.tableView_myLoan.footer = footer;
}

#pragma mark - 数据处理相关
#pragma mark 下拉刷新数据
- (void)loadNewData
{
    from=0;
    
//    [self.tableView_myLoan reloadData];
    
    [self DataSourceRequestHelpMeBagBankListView];
    
    // 拿到当前的下拉刷新控件，结束刷新状态
    [self.tableView_myLoan.header endRefreshing];
    
}

#pragma mark 上拉加载更多数据
- (void)loadMoreData
{
    from+=20;
    [self DataSourceRequestHelpMeBagBankListView];

}

#pragma mark -- 网络数据请求
- (void) DataSourceRequestHelpMeBagBankListView
{
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    NetworkStatus status = [reach currentReachabilityStatus];
    
    if (![UIView NetFromStatus:status]) {
       
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [UIView showAlertMsg:@"网络连接已断开" andShowBgColor:[UIColor blackColor] andLabelTectColor:[UIColor whiteColor]];
        
        return;
    }
    else
    {
        NSString *strUrl = [NSString stringWithFormat:@"%@loan/get",MRAPI];
        NSDictionary *paras_loan = @{@"memberid":[[NSUserDefaults standardUserDefaults] objectForKey:@"memberid"],@"from":[NSNumber numberWithInt:from],@"to":[NSNumber numberWithInt:20]};
        
        [[HttpRequest shardWebUtil] getNetworkRequestURLString:strUrl parameters:paras_loan success:^(id obj) {
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            
            NSLog(@"get%@",obj);
            
            NSString *str_false = obj[@"error"];
            
            if (str_false.length==0) {
                
                _dataCount=[obj[@"count"] intValue];
                /**
                 *  成功之后清理上一次数据
                 */
                [self.mutableArray_data removeAllObjects];

                NSArray *array_data = obj[@"data"];
                if (array_data.count!=0) {
                    for (int i=0; i<array_data.count; i++) {
                        MyLoanModel *model = [[MyLoanModel alloc] init];
                        [model decodeDic:array_data[i]];
                        [self.mutableArray_data addObject:model];
                    }
                    
                     [self.tableView_myLoan reloadData];
                    
                    if (self.mutableArray_data.count == _dataCount) {
                        [self.tableView_myLoan.footer noticeNoMoreData];
                    }
                    else
                    {
                        [self.tableView_myLoan.footer endRefreshing];
                    }
                    
                }
                else
                {
                    [BaseViewController showMessage:@"暂无数据"];
                }
            }
            else
            {
                [BaseViewController showMessage:str_false];
            }
            
        } fail:^(NSError *error) {
            NSLog(@"get%@",error);
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            [UIView showAlertMsg:@"网络请求超时"];
            
        }];
        
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}



@end
